<script setup>
import { watch } from 'vue'
const props = defineProps({
  value: {
    type: [String, Number],
    default: '',
  },
  placeholder: {
    type: String,
    default: '请填写',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
    default: 'text',
  },
  maxlength: {
    type: Number,
    default: 99999,
  },
  max: {
    type: Number,
    default: 0,
  },
  rightText: {
    type: String,
    default: '',
  },
  point: {
    type: Boolean,
    default: false,
  },
})

watch(props, (val) => {
  if (val.type === 'number' && props.point) {
    emit(
      'update:value',
      val.value.toString().replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    )
  }
})
const emit = defineEmits(['input', 'update:value'])
const id = 's' + Math.ceil(Math.random() * 10000000).toString()
function handleInput(val) {
  if (props.max) {
    if (val.target.value > props.max) {
      // console.log(props.max, `this is max`)
      document.querySelector(`#${id}`).value = props.max
      emit('update:value', props.max)
      emit('input', props.max)
    } else {
      emit('update:value', val.target.value)
      emit('input', val.target.value)
    }
  } else {
    emit('update:value', val.target.value)
    emit('input', val.target.value)
  }
}
</script>

<template>
  <div class="input-box fz-14">
    <input
      :id="id"
      :value="props.value"
      :type="props.type"
      :maxlength="maxlength"
      @input="handleInput"
      :placeholder="props.placeholder"
    />
    <span>{{ props.rightText }}</span>
    <slot />
  </div>
</template>

<style scoped lang="scss">
.input-box {
  position: relative;
  input {
    @include wh(100%, 0.36rem);
    border: 1px solid #ccc;
    border-radius: 0.04rem;
    padding: 0 0.1rem;
  }
  input::-webkit-input-placeholder {
    color: #999;
  }
  span {
    position: absolute;
    right: 0.1rem;
    top: 0.1rem;
    color: #999999;
  }
}
</style>
